package bean

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"strings"
	"user-agent/database"
	"user-agent/database/schema"
)

type UserAgentBean struct{}

var MODULE_USERAGENT_TABLE_NAME = "user_agent"

func (bean *UserAgentBean) GetAll() ([]schema.UserAgent, error) {
	engine := database.GetDriver()
	list := []schema.UserAgent{}
	sql := fmt.Sprintf(`SELECT * from %s`, MODULE_USERAGENT_TABLE_NAME)
	err := engine.SQL(sql).Find(&list)
	return list, err
}

func (bean *UserAgentBean) Insert(item *schema.UserAgent) error {
	engine := database.GetDriver()
	hash := md5.Sum([]byte(item.Agent))
	item.MD5 = hex.EncodeToString(hash[:])
	if strings.Contains(strings.ToLower(item.Agent), "mobile") {
		item.Type = "mobile"
	} else {
		item.Type = "pc"
	}
	_, err := engine.Insert(item)
	return err
}
